package com.app.couponsharelife.ui.main.special
import android.content.Intent
import android.graphics.Paint
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.baichuan.android.trade.AlibcTrade
import com.alibaba.baichuan.android.trade.callback.AlibcTradeCallback
import com.alibaba.baichuan.android.trade.model.AlibcShowParams
import com.alibaba.baichuan.android.trade.model.OpenType
import com.alibaba.baichuan.android.trade.page.AlibcPage
import com.alibaba.baichuan.trade.biz.AlibcConstants
import com.alibaba.baichuan.trade.biz.context.AlibcResultType
import com.alibaba.baichuan.trade.biz.context.AlibcTradeResult
import com.alibaba.baichuan.trade.biz.core.taoke.AlibcTaokeParams
import com.alibaba.baichuan.trade.biz.login.AlibcLogin
import com.alibaba.baichuan.trade.biz.login.AlibcLoginCallback
import com.app.couponsharelife.R
import com.app.couponsharelife.base.BaseActivity
import com.app.couponsharelife.data.bean.HomeChiocenGoodsBean
import com.app.couponsharelife.data.bean.RemoteResultBean
import com.app.couponsharelife.data.bean.TaobaoGoodBean
import com.app.couponsharelife.data.remote.retrofit.RetrofitWorker
import com.app.couponsharelife.data.remote.retrofit.exception.OtherException
import com.app.couponsharelife.manage.Contacts
import com.app.couponsharelife.ui.dialog.NewMenDialog
import com.app.couponsharelife.ui.listener.OnClickListener
import com.app.couponsharelife.ui.main.home.shopweb.WebActivity
import com.app.couponsharelife.ui.main.me.invite.ShareInvitePicActivity
import com.app.couponsharelife.utils.AppUtils
import com.app.couponsharelife.utils.DataUtils
import com.app.couponsharelife.utils.LoadUtils
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.observers.DisposableObserver
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.activity_newmen_free.*
import kotlinx.android.synthetic.main.base_title_white.*
import kotlinx.android.synthetic.main.rvitem_newmen_free.view.*
/**
 *Created by xct on 2019/5/16
 *Description:新人0元购
 */
class NewManFreeActivity:BaseActivity() {
    private var pageIndex=1
    private var goodsList= arrayListOf<TaobaoGoodBean>()
    private var adapter: MyAdapter?=null
    private var favoritesID=""
    private var name=""
    private var alibcShowParams: AlibcShowParams? = null//页面打开方式，默认，H5，Native
    private var exParams: HashMap<String, String>? = null//yhhpass参数
    private var alibcTaokeParams: AlibcTaokeParams? = null//淘客参数，包括pid，unionid，subPid
    override val viewLayoutId: Int
        get() = R.layout.activity_newmen_free

    override fun initViews() {
        AppUtils.initImmersionBar(this,true)
        favoritesID=intent.getStringExtra("FavoritesID")?:""
        name=intent.getStringExtra("Name")?:""
        basetitle_title.text=name
        adapter=MyAdapter()
        rvGoods.layoutManager= LinearLayoutManager(this)
        rvGoods.adapter=adapter
        getGoodsList()
        basetitle_llclose.setOnClickListener { finish() }
        llShare.setOnClickListener { goShare() }
    }
    private fun getGoodsList(){
        showProgressDialog("加载中...")
        val map=HashMap<String,String>()
        map["pageNo"]=pageIndex.toString()
        map["pageSize"]="10"
        map["userId"]=AppUtils.getString(Contacts.USERID,"")
        map["favoritesId"]=favoritesID
        RetrofitWorker.retrofitWorker.getFavoritesItemPage(map)
                .subscribeOn(Schedulers.io())
                .map { DataUtils().taobaoData(it) }
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object : DisposableObserver<RemoteResultBean<HomeChiocenGoodsBean>>(){
                    override fun onComplete() {

                    }

                    override fun onNext(it: RemoteResultBean<HomeChiocenGoodsBean>) {
                        dismissProgressDialog()
                        if (it.data!=null&&it.data!!.recordss.isNotEmpty()){
                            goodsList.clear()
                            goodsList.addAll(it.data!!.recordss)
                            adapter!!.notifyDataSetChanged()
                        }
                    }

                    override fun onError(e: Throwable) {
                        dismissProgressDialog()
                        if (e is OtherException){
                            showToastMsg(e.msg)
                        }else{
                            //Log.e("eee","---->"+e.toString())
                            showToastMsg("网络加载出错了！")
                        }
                    }

                })
    }
    private fun getIsNewMen(taobaoGoodBean:TaobaoGoodBean){
        showProgressDialog("加载中...")
        val map = java.util.HashMap<String, String>()
        map["userId"]=AppUtils.getString(Contacts.USERID,"")
        RetrofitWorker.retrofitWorker.getIsNewMen(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object :DisposableObserver<RemoteResultBean<String>>(){
                    override fun onComplete() {

                    }

                    override fun onNext(it: RemoteResultBean<String>) {
                        dismissProgressDialog()
                        if (200==it.code){
                            val relationId = AppUtils.getString(Contacts.ADZONE_ID, "")
                            if (relationId.isNotEmpty()) {
                                goTaoBao(taobaoGoodBean)
                            } else {
                                //getAliLonginUrl()
                                taobaoLogin()
                            }
                        }
                    }

                    override fun onError(e: Throwable) {
                        dismissProgressDialog()
                        if (e is OtherException){
                            if ("502"==e.code.toString()){
                                showNewMenDialog()
                            }else{
                                showToastMsg(e.msg)
                            }
                        }else{
                            showToastMsg("数据加载出错！")
                        }
                    }
                })
    }
    private fun getAliLonginUrl(){
        showProgressDialog("加载中...")
        val map = java.util.HashMap<String, String>()
        map["userId"]=AppUtils.getString(Contacts.USERID,"")
        RetrofitWorker.retrofitWorker.getAuthUrl(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object :DisposableObserver<RemoteResultBean<String>>(){
                    override fun onComplete() {

                    }

                    override fun onNext(it: RemoteResultBean<String>) {
                        dismissProgressDialog()
                        if (200==it.code){
                            val url=it.data?:""
                            if (url.isNotEmpty()){
                                val intent= Intent(this@NewManFreeActivity, WebActivity::class.java)
                                intent.putExtra("url", url)
                                intent.putExtra("name", "淘宝授权")
                                startActivity(intent)
                            }
                        }
                    }

                    override fun onError(e: Throwable) {
                        dismissProgressDialog()
                        if (e is OtherException){
                            if ("502"==e.code.toString()){

                            }else{
                                showToastMsg(e.msg)
                            }
                        }else{
                            showToastMsg("数据加载出错！")
                        }
                    }
                })
    }
    private fun goShare(){
        startActivity(Intent(this, ShareInvitePicActivity::class.java))
    }
    private fun showNewMenDialog(){
        NewMenDialog(this,R.style.DialogStyle,object : OnClickListener {
            override fun click(arg1: Int, arg2: Any) {
                goShare()
            }
        }).show()
    }
    private fun taobaoLogin(){
        showProgressDialog("请稍后")
        val alibcLogin = AlibcLogin.getInstance()
        alibcLogin.showLogin(object : AlibcLoginCallback {
            override fun onSuccess(p0: Int) {
                //showToastMsg("登录成功 ")
                //获取淘宝用户信息
                //Log.i("eee", "获取淘宝用户信息: "+AlibcLogin.getInstance().session)
                dismissProgressDialog()
                //getAliLoginUrl()
                getAliLonginUrl()
            }

            override fun onFailure(p0: Int, p1: String?) {
                //showToastMsg("登录失败")
                dismissProgressDialog()
            }
        })
    }
    private fun goTaoBao(goodBean:TaobaoGoodBean) {
        showCountDownProgressDialog("请稍候", 3)
        alibcShowParams = AlibcShowParams(OpenType.Native, false)
        exParams = HashMap()
        exParams!![AlibcConstants.ISV_CODE] = "appisvcode"
        exParams!!["alibaba"] = "阿里巴巴"//自定义参数部分，可任意增删改
        // 若非淘客taokeParams设置为null即可
        val pid = Contacts.ALIMAMA_PID //+ AppUtils.getString(Contacts.ADZONE_ID, "")
        alibcTaokeParams = AlibcTaokeParams()
        alibcTaokeParams?.adzoneid = "65231850041"//AppUtils.getString(Contacts.ADZONE_ID, "")
        alibcTaokeParams?.pid = pid
        alibcTaokeParams?.subPid = pid
        alibcTaokeParams?.extraParams = java.util.HashMap()
        (alibcTaokeParams?.extraParams as java.util.HashMap<String, String>)["taokeAppkey"] = Contacts.APP_ID
        (alibcTaokeParams?.extraParams as java.util.HashMap<String, String>)["relationId"] = AppUtils.getString(Contacts.ADZONE_ID, "")
        val url = if (goodBean!!.coupon_share_url_new != "") goodBean!!.coupon_share_url_new else {
            if (goodBean!!.coupon_share_url != "https:" && goodBean!!.coupon_share_url != "") goodBean!!.coupon_share_url else goodBean!!.url
        }
        if (url == "") {
            showToastMsg("该商品暂时不能购买")
            return
        }
        AlibcTrade.show(this, AlibcPage(url+"&relationId=${AppUtils.getString(Contacts.ADZONE_ID, "")}"), alibcShowParams, alibcTaokeParams, exParams, object : AlibcTradeCallback {
            override fun onTradeSuccess(tradeResult: AlibcTradeResult) {
                //当addCartPage加购成功和其他page支付成功的时候会回调
                if (tradeResult.resultType == AlibcResultType.TYPECART) {
                    //加购成功
                    showToastMsg("加购成功")
                } else if (tradeResult.resultType == AlibcResultType.TYPEPAY) {
                    //支付成功
//                    Log.d("order", tradeResult.payResult.paySuccessOrders[0])
                }
            }

            override fun onFailure(errCode: Int, errMsg: String) {
                showToastMsg("电商SDK出错,错误码=$errCode / 错误消息=$errMsg")
            }
        })
    }
    override fun onDestroy() {
        super.onDestroy()
        AppUtils.destroyImmersionBar(this)
    }
    private inner class MyAdapter:RecyclerView.Adapter<MyHolder>(){
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyHolder {
            val view= LayoutInflater.from(parent.context).inflate(R.layout.rvitem_newmen_free, parent, false)
            return MyHolder(view)
        }

        override fun getItemCount(): Int {
            return goodsList.size
        }

        override fun onBindViewHolder(holder: MyHolder, position: Int) {
            if (goodsList.isNotEmpty()){
                val taobaoGoodBean=goodsList[position]
                holder.goodsTitle!!.text = "              ${taobaoGoodBean.title}"
                LoadUtils().loadRoundImag(this@NewManFreeActivity,holder.goodsImag!!,taobaoGoodBean.pict_url as String,R.drawable.ic_app_place_holder3,5)
                val price=taobaoGoodBean.final_price
                holder.goodsOldPrice!!.text=price
                holder.goodsFL!!.text="补贴￥${price}"
                holder.goodsFK!!.text="先付后补￥${price}"
                if (taobaoGoodBean.has_coupon){
                    holder.goodsYHQPrice!!.text=String.format("¥%s", taobaoGoodBean.coupon_price)
                    holder.couponLL!!.visibility=View.VISIBLE
                }else{
                    holder.couponLL!!.visibility=View.INVISIBLE
                }

                holder.itemView.setOnClickListener {
                    getIsNewMen(taobaoGoodBean)
                }
            }
        }

    }
    private inner class MyHolder(itemview:View):RecyclerView.ViewHolder(itemview){
        var goodsImag: ImageView?=null
        var goodsTitle: TextView?=null
        var goodsOldPrice:TextView?=null
        var goodsOldPriceType:TextView?=null
        var goodsFL:TextView?=null
        var goodsFK:TextView?=null
        var goodsYHQPrice:TextView?=null
        var goodsXLNumber:TextView?=null
        var tvGoodsType:TextView?=null
        var couponLL: LinearLayout?=null
        init {
            goodsImag=itemView.ivGoodImage
            goodsTitle=itemView.tvGoodName
            goodsOldPrice=itemView.tvGoodSvipProfit
            goodsOldPriceType=itemView.tvGoodtype
            goodsFL=itemView.tvGoodVipProfit
            goodsFK=itemview.tvCouponPriceTitle
            goodsYHQPrice=itemView.tvCouponAmount
            goodsXLNumber=itemView.tvGoodVolume
            tvGoodsType=itemview.tvGoodtype
            couponLL=itemView.choiceness_rvitm_llq1
            tvGoodsType!!.paint.flags = Paint.STRIKE_THRU_TEXT_FLAG or Paint.ANTI_ALIAS_FLAG
            goodsOldPrice!!.paint.flags = Paint.STRIKE_THRU_TEXT_FLAG or Paint.ANTI_ALIAS_FLAG
        }
    }
}